package com.ninelock.config;

import com.ninelock.config.jwt.JwtTokenEnhancer;
import com.ninelock.properties.OAuth2Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * @ClassName TokenStoreConfig @Description 两种存储Token的存储模式：一种是用redis存储；一种是jwt模式
 *
 * @author gongym
 * @date 2018年11月13日 上午9:19:52
 */
@Configuration
public class TokenStoreConfig {
  /** redis连接工厂 */
  @Autowired private RedisConnectionFactory redisConnectionFactory;

  /**
   * 用于存放token
   *
   * @return
   */
  @Bean
  @ConditionalOnProperty(
      prefix = "sso.security.oauth2",
      name = "storeType",
      havingValue = "redis",
    matchIfMissing = true)
  public TokenStore redisTokenStore() {
    return new RedisTokenStore(redisConnectionFactory);
  }

  /** jwt TOKEN配置信息 */
//  @Configuration
  @ConditionalOnProperty(
      prefix = "sso.security.oauth2",
      name = "storeType",
      havingValue = "jwt",
      matchIfMissing = true)
  public static class JwtTokenConfig {
    @Autowired private OAuth2Properties oAuth2Properties;

    /**
     * 使用jwtTokenStore存储token
     *
     * @return
     */
    @Bean
    public TokenStore jwtTokenStore() {
      return new JwtTokenStore(jwtAccessTokenConverter());
    }
    /**
     * 用于生成jwt
     *
     * @return
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
      JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
      accessTokenConverter.setSigningKey(oAuth2Properties.getJwtSigningKey());
      return accessTokenConverter;
    }
    /**
     * 用于扩展JWT
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(name = "jwtTokenEnhancer")
    public TokenEnhancer jwtTokenEnhancer() {
      return new JwtTokenEnhancer();
    }
  }
}
